function ismobile() {

    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE�ں�
                presto: u.indexOf('Presto') > -1, //opera�ں�
                webKit: u.indexOf('AppleWebKit') > -1, //ƻ�����ȸ��ں�
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//����ں�
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //�Ƿ�Ϊ�ƶ��ն�
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios�ն�
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android�ն�
                iPhone: u.indexOf('iPhone') > -1, //�Ƿ�ΪiPhone����QQHD�����
                iPad: u.indexOf('iPad') > -1, //�Ƿ�iPad
                webApp: u.indexOf('Safari') == -1, //�Ƿ�webӦ�ó���û��ͷ����ײ�
                weixin: u.indexOf('MicroMessenger') > -1, //�Ƿ�΢�� ��2015-01-22������
                qq: u.match(/\sQQ/i) == " qq" //�Ƿ�QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };

    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}

var isMobile = ismobile();


//$(function () {

var totalPrice, useCoupon, token, address;

//getOrderId()

//getDetail({
//
//    "TOKEN": "D862733A-2790-5B20-2441-31BC86415241",
//    "need_addr": "海淀区",
//    "uid": 30,
//    "goods_id": 55,
//    "meal": {"name": "商品测试名称", "data_type": "2388", "id": 0, "worth": 3000},
//    "startTime": "2017-12-27 12:30",
//    "endTime": "2018-01-27 16:30",
//    "money": "4500"
//
//})

//});

if (isMobile == 0) {

    window.android.getAndroidOrderId("okok");
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallSiteListModel.postMessage(message);
}

function getOrderId() {

    if (isMobile == 1) {

        CallSiteListModel.jsCallOCWithSendId("ok");

    } else if (isMobile == 0) {

        window.android.getAndroidOrderId("okok");
    }
}

function receiveAndroidOrderId(k) {

    var obj = $.parseJSON(k);

    address = obj.need_addr;

    token = obj.TOKEN;

    getDetail(obj);

    totalPrice = obj.money;

    useCoupon = 100;

}

function receiveiOSVcData(i) {

    var obj = $.parseJSON(i);

    address = obj.need_addr;

    token = obj.TOKEN;

    getDetail(obj);

    totalPrice = obj.money;

    useCoupon = 100;

}

function getDetail(params) {

    $.ajax({

        type: "post",

        url: url + "users/goodsinfo",

        dataType: "json",

        data: {

            "goods_id": params.goods_id
        },

        beforeSend: function (xhr) {

        },

        success: function (result) {

            //console.log(result)

            if (result.codes == 200) {

                Object.assign(result, params);

                var html = template("OrderTpl", result);

                $("#order_body").html(html);

                defaultAddress(params.uid);


                if (isiphoneX) {

                    $("#order_footer").removeClass("order_footer_position");

                    $(".moneyDetail").css("margin-bottom", "0.427rem")

                } else {

                    $("#order_footer").addClass("order_footer_position")
                }

                $(".date").html("日期：" + result.startTime.slice(5) + " ~ " + result.endTime.slice(5));//日期

                var money = totalPrice.slice(1);//商品价格

                var cash_pledge = Number($(".cash_pledge").html());//押金

                // var insurance = parseFloat($(".insurance").html());// 保险

                var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

                $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice).toFixed(2));//总价

                $(".order_address").on("click", function () { //调哪个类

                    if (isMobile == 1) {

                        var message = {

                            "VcData": {

                                "contacts": contacts,

                                "iphone": iphone,

                                "addressTitle": address3,

                                "addressDetails": address2
                            },

                            "VcName": "AddressManager",

                            "VcWay": "AddAddress"
                        };

                        window.webkit.messageHandlers.CallSiteListModel.postMessage(message);

                        //CallSiteListModel.jsCalliOSWithAddAddress({
                        //
                        //    "VcData": {
                        //
                        //        "contacts": contacts,
                        //
                        //        "iphone": iphone,
                        //
                        //        "addressTitle": address3,
                        //
                        //        "addressDetails": address2
                        //
                        //    }, "VcName": "AddressManager"
                        //})
                    } else if (isMobile == 0) {

                        var json = {

                            "contacts": contacts,

                            "iphone": iphone,

                            "address": address4,

                            "province": address2,

                            "city": address3
                        };

                        window.android.jumpToProjectAdress(JSON.stringify(json));
                    }
                });

                $(".order_coupon").on("click", function () {//调哪个类

                    var json = {

                        "uid": result.uid,

                        "Tprice": money,

                        "type": [10, 600]
                    };

                    if (isMobile == 1) {


                        var message = {

                            "VcData": json,

                            "VcWay": "OrderCoupons"
                        };

                        window.webkit.messageHandlers.CallSiteListModel.postMessage(message);


                    } else if (isMobile == 0) {

                        window.android.showCoupon(JSON.stringify(json));
                    }
                });

                //点击订单中的提交订单，跳转支付页面，获取ios和Android的信息
                var flag = true;

                $(".submit").on("click", function () {//检测开始时间    结束时间

                    var timeStart = result.startTime.replace(/-/g, "/");

                    var timeEnd = result.endTime.replace(/-/g, "/");

                    var timestampStart = Date.parse(new Date(timeStart)) / 1000;//开始时间    时间戳

                    var timestampEnd = Date.parse(new Date(timeEnd)) / 1000;    //结束时间    时间戳

                    var timestampNow = Date.parse(new Date()) / 1000;          //当前时间     时间戳

                    //开始时间要大于当前时间  结束时间只能大于开始时间3个月

                    var timeLag = timestampEnd - timestampStart;

                    var timeDistance = (mGetDate(1) + mGetDate(2) + mGetDate(3)) * 24 * 60 * 60;

                    var length = $(".address_phone").html().length;

                    if (flag && length > 0 && timestampNow < timestampStart && timeLag < timeDistance && timestampEnd > timestampStart) {

                        var cid;

                        if (useCoupon == 100) {

                            ordermake(
                                result.uid,

                                $(".order_price").html().slice(5),

                                $(".address_contacts b").html(),

                                $(".address_phone").html(),

                                $(".serviceAddress b").html(),

                                useCoupon,

                                result.goods_id,

                                1,

                                timeFormatDate(timeStart),

                                timeFormatDate(timeEnd),

                                address,

                                result.meal.id,

                                token,

                                cid
                            )

                        } else if (useCoupon == 200) {

                            cid = $(".order_coupon").attr("id");//获取优惠券id

                            ordermake(
                                result.uid,

                                $(".order_price").html().slice(5),

                                $(".address_contacts b").html(),

                                $(".address_phone").html(),

                                $(".serviceAddress b").html(),

                                useCoupon,

                                result.goods_id,

                                1,

                                timeFormatDate(timeStart),

                                timeFormatDate(timeEnd),

                                address,

                                result.meal.id,

                                token,

                                cid
                            )
                        }
                        flag = false;

                        setTimeout(function () {

                            flag = true;

                        }, 1000);//点击后相隔多长时间可执行

                    } else {

                        if (timestampStart < timestampNow) {

                            if (isMobile == 1) {

                                window.webkit.messageHandlers.CallSiteListModel.postMessage({
                                    "VcData": "开始时间不能小于当前时间",
                                    "VcWay": "ShowMessage"
                                });

                                //CallSiteListModel.jsCalliOSWithShowMessage("开始时间不能小于当前时间");

                            } else if (isMobile == 0) {

                                window.android.toastMsg("开始时间不能小于当前时间");

                            }
                        } else if (timeLag > timeDistance) {

                            if (isMobile == 1) {

                                window.webkit.messageHandlers.CallSiteListModel.postMessage({
                                    "VcData": "结束时间不能大于开始时间的90天",
                                    "VcWay": "ShowMessage"
                                });

                                //CallSiteListModel.jsCalliOSWithShowMessage("结束时间不能大于开始时间的90天");

                            } else if (isMobile == 0) {

                                window.android.toastMsg("结束时间不能大于开始时间的90天");

                            }
                        } else if (timestampEnd < timestampStart) {//结束时间小于开始时间

                            if (isMobile == 1) {

                                window.webkit.messageHandlers.CallSiteListModel.postMessage({
                                    "VcData": "结束时间不能小于开始时间",
                                    "VcWay": "ShowMessage"
                                });

                                //CallSiteListModel.jsCalliOSWithShowMessage("结束时间不能小于开始时间");

                            } else if (isMobile == 0) {

                                window.android.toastMsg("结束时间不能小于开始时间");

                            }
                        } else if (length <= 0) {

                            if (isMobile == 1) {

                                window.webkit.messageHandlers.CallSiteListModel.postMessage({
                                    "VcData": "收货地址不能为空",
                                    "VcWay": "ShowMessage"
                                });

                                //CallSiteListModel.jsCalliOSWithShowMessage("收货地址不能为空");

                            } else if (isMobile == 0) {

                                window.android.toastMsg("收货地址不能为空");
                            }
                        }

                    }

                });

                //点击跳转协议
                //$(".xieyi").on("click", function () {
                //
                //    var json = {
                //        "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",
                //
                //        "titleName": "用户租赁协议"
                //    };
                //
                //    if (isMobile == 1) {
                //
                //        var message = {
                //
                //            "VcData": json,
                //
                //            "VcName": "PublicWeb",
                //
                //            "VcWay": "PushVCName"
                //        };
                //
                //        window.webkit.messageHandlers.CallSiteListModel.postMessage(message);
                //
                //    } else if (isMobile == 0) {
                //
                //        window.android.toRule(JSON.stringify(json))
                //    }
                //})


            }

        },
        error: function (info) {

            console.log(info)
        }
    })

}

function defaultAddress(uid) {

    $.ajax({

        url: url + "users/fourModel",

        type: "POST",

        dataType: "json",

        data: {

            "url": "address/lists",

            "uid": uid,

            "addr_type": 1

        },

        success: function (data) {

            if (data.codes == 200) {

                var list = data.data.list[0];

                $(".address_contacts b").html(list.link_man);

                $(".address_phone").html(list.link_mobile);

                $(".serviceAddress b").html(list.shipping_address);

                $(".address").css("margin-left", "0")

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallSiteListModel.postMessage({
                    "VcData": "地址获取失败",
                    "VcWay": "ShowMessage"
                });

                //CallSiteListModel.jsCalliOSWithShowMessage("地址获取失败");

            } else if (isMobile == 0) {

                window.android.toastMsg("地址获取失败");
            }
        }
    });
}

//订单收货地址
var address1 = "", address2 = "", address3 = "", address4 = "", contacts = "", contacts1 = "", iphone = "";

function receiveiOSAddAddress(a) {

    var result = JSON.parse(a);

    $(".serviceAddress b").html(result['shipping_address']);

    contacts = result['link_man'];

    $(".address_contacts b").html(result['link_man']);

    iphone = result['link_mobile'];

    $(".address").css("margin-left", "0");

    $(".address_phone").html(result['link_mobile']);

}

function receive_android_addAddress(k) {

    var result = JSON.parse(k);
    
    //console.log(result)

    $(".serviceAddress b").html(result.province + result.city +result.district+ result.address);

    address2 = result.province;

    address3 = result.city;

    address4 = result.address;

    contacts = result.contacts;

    $(".address_contacts b").html(result.contacts);

    $(".address_phone").html(result.iphone);

    iphone = result.iphone;

    $(".address").css("margin-left", "0");

}

function receiveiOSOrderCoupon(a) {

    var obj = $.parseJSON(a);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.id);

        // alert(useCoupon)

        var money = totalPrice.slice(1);//商品价格

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseFloat($(".insurance").html());// 保险

        var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

        $(".couponMoney").html(couponPrice);//优惠金额

        // alert( couponPrice.toFixed(2))

        $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice));//总价

    } else {

        useCoupon = 100;

        $(".couponPrice ").html("请选择");

    }
}

function receive_android_orderCoupon(k) {

    var obj = $.parseJSON(k);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.cid);

        //alert($(".order_coupon").attr("id"))

        var money = totalPrice.slice(1);//商品价格

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseInt($(".insurance").html());// 保险

        var couponPrice = Number($(".couponPrice").html()) || 0;//优惠券

        $(".couponMoney").html(couponPrice);//优惠金额

        // alert( couponPrice.toFixed(2))

        $(".order_price").html("实付款:￥" + (Number(money) + cash_pledge - couponPrice));//总价

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");

        // alert(useCoupon)
    }
}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    };

    var newDate = new Date();

    newDate.setTime(tmpTime);

    return newDate.format('yyyyMMddhhmm');
}
//获取当前月的天数，下月，下下月的总和
function mGetDate(n) {

    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + n;

    if (month > 12) {

        year++;

        month = month - 12;
    }
    var d = new Date(year, month, 0);

    return d.getDate();
}
//下单
function ordermake(uid, total_money, receive_user_name, receive_user_mobile, receive_user_addr, useCoupon, goods_id, need_number, start_time, end_time, need_addr_id, meal_id, token, cid) {

    //alert(uid+"--"+ total_money+"--"+ receive_user_name+"--"+receive_user_mobile+"--"+receive_user_addr+"--"+ useCoupon+"--"+ goods_id+"--"+ need_number+"--"+ start_time+"--"+end_time+"--"+ need_addr_id+"--"+ meal_id+"--"+ token+"--"+ time_long_id+"--"+ cid);

    $.ajax({

        type: "POST",

        url: url + "users/ordermake",

        dataType: "json",

        data: {

            "uid": uid,

            "total_money": total_money,

            "receive_user_name": receive_user_name,

            "receive_user_mobile": receive_user_mobile,

            "receive_user_addr": receive_user_addr,

            "use_coupon": useCoupon,//默认不使用 值为100

            "coupon_id": cid,

            "order_info": [
                {
                    "goods_id": goods_id,

                    "need_number": need_number,

                    "start_time": start_time,

                    "end_time": end_time,

                    "need_addr_id": need_addr_id,

                    "meal_id": meal_id,

                    "belong_model": 600,


                }
            ]
        },

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            if (data.codes == "200") {

                if (isMobile == 1) {

                    var message = {

                        "VcData":  {"order_code": data.data.order_code},

                        "VcName": "ListPay",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallSiteListModel.postMessage(message);


                    //CallSiteListModel.jsCalliOSWithPushVCName({
                    //
                    //    "VcData": {"order_code": data.data.order_code},
                    //
                    //    "VcName": "ListPay"
                    //});
                } else if (isMobile == 0) {

                    window.android.jumptoOrderActivity(data.data.order_code);

                }
            } else if (data.codes != "200" && data.codes) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallSiteListModel.postMessage({"VcData": data.msg, "VcWay": "ShowMessage"});

                    //CallSiteListModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);

                }
            } else if (data.codes == null) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallSiteListModel.postMessage({"VcData": "系统繁忙，请稍后重试", "VcWay": "ShowMessage"});

                    //CallSiteListModel.jsCalliOSWithShowMessage("系统繁忙，请稍后重试");

                } else if (isMobile == 0) {

                    window.android.toastMsg("系统繁忙，请稍后重试");
                }
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallSiteListModel.postMessage({"VcData": "请检查网络", "VcWay": "ShowMessage"});

                //CallSiteListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    });
}